import { useWsStore } from "@/stores/ws"

let socket: WebSocket | null = null

// 心跳检测的定时器 变量
type TimerType = ReturnType<typeof setInterval> | null
let timer: TimerType = null
// 心跳状态
let isAlive: boolean = true
// 重连次数的变量
let connectNum: number = 10
// 实际重连次数
let realConnectNum: number = 1
// 链接状态太
let isLink: boolean = false
function initWs(): void {
    const wsStore = useWsStore()
    socket = new WebSocket("ws://127.0.0.1:3000");

    socket.onopen = (): void => {
        isLink = true
        log("链接创建成功！")
        timer = setInterval(() => {
            if (isAlive) {
                sendMsg({ type: 'ping' })
                isAlive = false
            } else {
                // 清空定时器
                clearInterval(timer as NodeJS.Timeout)
                timer = null
                isLink = false
            }
        }, 3000)
    }

    socket.onmessage = (evt: MessageEvent): void => {
        let data: any
        try {
            data = JSON.parse(evt.data)
        } catch (error) {
            data = { type: 'error', data: null }
        }
        // console.log(data, 20)
        if (data.type === 'pong') {
            isAlive = true
        } else if(data.type==='friendList'){
            wsStore.setResource('friendList', data.data.list)
        }else if(data.type==='msg'){
            console.log(data.data,49)
            wsStore.setResource('chatList_'+data.data.send_uid, data.data,'append')
            console.log(wsStore.resource)
        }else if(data.type==='getMsg'){
            console.log(data.data,53)
            if(data.data.length>0){
                if(wsStore.uid===data.data[0].send_uid){
                    wsStore.setResource('chatList_'+data.data[0].send_uid, data.data)
                }else{
                    wsStore.setResource('chatList_'+data.data[0].get_uid, data.data)
                }
                console.log(wsStore.resource,60)
            }
            // wsStore.setResource('chatList_'+data.data.send_uid, data.data)
        }

    }

    socket.onclose = async (): Promise<void> => {
        log("链接关闭！")
        isLink = false
        if (realConnectNum <= connectNum) {
            log(`正在尝试第${realConnectNum}次重连...`)
            initWs()
            realConnectNum++
            await wait(3)
        }
    }
}

function wait(s: number): Promise<void> {
    return new Promise<void>((resolve) => {
        setTimeout(() => {
            resolve()
        }, s * 1000)
    })
}

interface SendMsgObj {
    type: string
    [key: string]: any
}

function sendMsg(obj: SendMsgObj): void {
    if (!isLink || !socket) {
        logErr("socket未初始化！")
    } else {
        socket.send(JSON.stringify(obj))
    }

}

function log(text: string): void {
    console.log(`%c${text}`, 'color: green; font-weight: bold;');
}

function logErr(text: string): void {
    console.log(`%c${text}`, 'color: red; font-weight: bold;');
}

export {
    initWs, sendMsg
}